import React, { PureComponent, Fragment } from 'react';
import dynamic from 'umi/dynamic';
import { connect } from 'dva';
import QueueAnim from 'rc-queue-anim';
import OverPack from 'rc-scroll-anim/lib/ScrollOverPack';
import moment from 'moment';

import { Form, Input, DatePicker, TimePicker, Select, Button, Card, InputNumber, Radio, Icon, Tooltip, Modal, message } from 'antd';

import DescriptionList from '@/components/DescriptionList';
import ImageCrop from '@/components/ImageCrop';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const { Description } = DescriptionList;

let goodsPrizesIds = 1;
let goodsFiguresIds = 1;

const disabledDate = current => current && current < moment().endOf('day');

@connect(({ user, goodsAdd, loading }) => ({
  user,
  goodsAdd,
  submitting: loading.models.goodsAdd,
}))
@Form.create()
class BasicForms extends PureComponent {

  state = {
    modalVisible: false,
    style: '',
    GoodsPrizes: [],
    GoodsFigures: [],
    jiade: 0
  }

  componentWillMount() {
    goodsPrizesIds = 1;
    goodsFiguresIds = 1;
  }

  componentDidMount() {
    const { queryRow = {} } = this.props;
    const { GoodsPrizes = [], GoodsFigures = [] } = queryRow;
    this.setState(state => ({
      ...state,
      GoodsPrizes,
      GoodsFigures
    }))
  }

  handleSubmit = (goodsId, e) => {
    e.preventDefault();

    const { GoodsPrizes = [], GoodsFigures = [] } = this.state;
    const { dispatch, form, user, goodsAdd: { data = {} }, parentVisable } = this.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        const titles = fieldsValue.titles.filter(i => i);
        const numbers = fieldsValue.numbers.filter(i => i);
        const goodsPrizes = GoodsPrizes.map((item, index) => ({
          ...(item.id ? { id: item.id, goodsId: item.goodsId } : {}),
          cover: item.cover,
          title: titles[index],
          number: numbers[index],
        }));
        const images = fieldsValue.images.filter(i => i);
        const figcaptions = fieldsValue.figcaptions.filter(i => i);
        const goodsFigures = GoodsFigures.map((item, index) => ({
          ...(item.id ? { id: item.id, goodsId: item.goodsId } : {}),
          image: item.image,
          figcaption: figcaptions[index],
        }));
        const payload = {
          nickname: user.currentUser.name,
          userId: user.currentUser.id,
          brief: fieldsValue.brief,
          sponsor: fieldsValue.sponsor,
          style: fieldsValue.style,
          number: fieldsValue.number,
          endAt: fieldsValue.endAt && fieldsValue.endAt.format('YYYY-MM-DD hh:mm:ss'),
          GoodsPrizes: goodsPrizes,
          GoodsFigures: goodsFigures,
        }
        // console.log(JSON.stringify(payload), 'goodsId')
        // return
        if (goodsId) {
          dispatch({
            type: 'goodsAdd/update',
            payload: { ...payload, isEdit: true, id: goodsId },
            callback({ errno, data, errmsg }) {
              if (errno) {
                message.error(errmsg || '更新失败');
              } else {
                dispatch({
                  type: 'goods/fetch'
                });
                parentVisable();
                message.success('奖品更新成功~');
              }
            }
          });
        } else {
          dispatch({
            type: 'goodsAdd/add',
            payload,
            callback({ errno, data, errmsg }) {
              if (errno) {
                message.error(errmsg || '提交失败');
              } else {
                dispatch({
                  type: 'goods/fetch'
                });
                parentVisable();
                message.success('奖品上传成功~');
              }
            }
          });
        }
      }
    });
  };

  handleUpload = (index = 0, info = {}) => {
    const { form } = this.props;

    const { errno = -1, data = {} } = info;
    const { name = '' } = info.data;
    if (!errno) {
      const { GoodsPrizes = [] } = this.state;
      const itemObj = GoodsPrizes[index - 1] || {};
      itemObj.cover = name;
      GoodsPrizes.splice(index - 1, 1, itemObj);

      // console.log(form.getFieldValue(`covers`), 111)

      this.setState(state => ({
        ...state,
        jiade: state.jiade + 1,
        GoodsPrizes
      }));
    }
  }

  handleUpload2 = (index = 0, info = {}) => {
    const { form } = this.props;

    const { errno = -1, data = {} } = info;
    const { name = '' } = info.data;
    if (!errno) {
      const { GoodsFigures = [] } = this.state;
      const itemObj = GoodsFigures[index - 1] || {};
      itemObj.image = name;
      GoodsFigures.splice(index - 1, 1, itemObj);

      // console.log(form.getFieldValue(`covers`), 111)

      this.setState(state => ({
        ...state,
        jiade: state.jiade + 1,
        GoodsFigures
      }));
    }
  }

  remove = (k) => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  }

  add = () => {
    const { form, queryRow } = this.props;
    const keys = form.getFieldValue('keys');
    if (queryRow.GoodsPrizes) return message.error('只能修改不能新增！');
    if (goodsPrizesIds >= 3) return message.error('奖品最多添加三件！');
    const nextKeys = keys.concat(++goodsPrizesIds);
    form.setFieldsValue({
      keys: nextKeys,
    });
  }

  addImageText = () => {
    const { form, queryRow } = this.props;
    const keys2 = form.getFieldValue('keys2');
    if (queryRow.GoodsFigures) return message.error('只能修改不能新增！');
    if (goodsFiguresIds >= 3) return message.error('奖品图文介绍最多添加三件！');
    const nextKeys2 = keys2.concat(++goodsFiguresIds);
    form.setFieldsValue({
      keys2: nextKeys2,
    });
  }

  render() {
    const { modalVisible } = this.state;
    const { queryRow = {} } = this.props;

    const {
      submitting,
      form: { getFieldDecorator, getFieldValue },
      goodsAdd: { data },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    goodsPrizesIds = queryRow.GoodsPrizes && queryRow.GoodsPrizes.length ? queryRow.GoodsPrizes.length : goodsPrizesIds;
    const initialGoodsPrizesArray = [];
    for (let i = 0; i < goodsPrizesIds; i++) initialGoodsPrizesArray.push(i + 1);

    getFieldDecorator('keys', { initialValue: initialGoodsPrizesArray });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => {
      const normalizeValue = queryRow.GoodsPrizes ? queryRow.GoodsPrizes[k - 1] : {};
      return (
        <section key={k}>
          <FormItem {...formItemLayout} label="奖品图片" style={{marginBottom: 16}}>
            {getFieldDecorator(`covers[${k}]`, {
              initialValue: (normalizeValue ? normalizeValue.cover : ''),
              rules: [
                { required: true, message: "请输入奖品图片", },
              ],
            })(
            <ImageCrop
              listType="picture-card"
              onUpload={this.handleUpload.bind(null, k)}
            >
              {
                (this.state.GoodsPrizes[index] && this.state.GoodsPrizes[index].cover)
                ?
                <img src={this.state.GoodsPrizes[index].cover} width="200" />
                :
                (normalizeValue && normalizeValue.cover)
                ? 
                <img src={normalizeValue.cover} width="200" />
                : 
                <Icon type="plus" />
              }
            </ImageCrop>
          )}
          </FormItem>
          <FormItem {...formItemLayout} label="奖品名称">
            {getFieldDecorator(`titles[${k}]`, {
              initialValue: (normalizeValue && normalizeValue.title)  ? normalizeValue.title : '',
              rules: [
                { required: true, message: "请输入8~16个字符的奖品名称", min: 8, max: 16 },
              ],
              rules: [{required: true, message: "请输入奖品名称"}],
            })(<Input placeholder="请输入奖品名称" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="奖品数量">
            {getFieldDecorator(`numbers[${k}]`, {
              initialValue: normalizeValue && normalizeValue.number || '1',
              rules: [
                { required: true, message: "请输入奖品数量", },
              ],
            })(<InputNumber placeholder="请输入奖品数量" min={1} max={10000} style={{width: '100%'}} />)}
          </FormItem>
        </section>
      )
    });

    goodsFiguresIds = queryRow.GoodsFigures && queryRow.GoodsFigures.length ? queryRow.GoodsFigures.length : goodsFiguresIds;
    const initialGoodsFiguresArray = [];
    for (let i = 0; i < goodsFiguresIds; i++) initialGoodsFiguresArray.push(i + 1);
    getFieldDecorator('keys2', { initialValue: initialGoodsFiguresArray });
    const keys2 = getFieldValue('keys2');
    const formItems2 = keys2.map((k, index) => {
      const normalizeValue = queryRow.GoodsFigures ? queryRow.GoodsFigures[k - 1] : {};
      return (
        <section key={'_' + k}>
          <FormItem {...formItemLayout} label="介绍图片" style={{marginBottom: 16}}>
            {getFieldDecorator(`images[${k}]`, {
              initialValue: (normalizeValue ? normalizeValue.image : ''),
              rules: [
                { required: true, message: "请输入图文介绍图片", },
              ],
            })(
            <ImageCrop
              listType="picture-card"
              onUpload={this.handleUpload2.bind(null, k)}
            >
              {
                (this.state.GoodsFigures[index] && this.state.GoodsFigures[index].image)
                ?
                <img src={this.state.GoodsFigures[index].image} width="200" />
                :
                (normalizeValue && normalizeValue.image)
                ? 
                <img src={normalizeValue.image} width="200" />
                : 
                <Icon type="plus" />
              }
            </ImageCrop>
          )}
          </FormItem>
          <FormItem {...formItemLayout} label="介绍文字">
            {getFieldDecorator(`figcaptions[${k}]`, {
              initialValue: normalizeValue ? normalizeValue.figcaption: '',
              rules: [
                { required: true, message: "请输入图文介绍文字", },
              ],
            })(<TextArea placeholder="请输入图文介绍文字" rows={2} />)}
          </FormItem>
        </section>
      )
    });

    return (
      <Fragment>
        <Card title={queryRow.id ? '编辑抽奖' : '新增抽奖'} bordered={false}>
          <QueueAnim delay={300} component={Form} onSubmit={this.handleSubmit.bind(null, queryRow.id)} hideRequiredMark style={{ minHeight: 300, marginTop: 8 }}>
            {formItems}
            <FormItem {...submitFormLayout}>
              <Button type="dashed" onClick={this.add} style={{ width: '100%' }}>
                <Icon type="plus" /> 增加奖品
              </Button>
            </FormItem>
            <FormItem {...formItemLayout} label="发起人" key="sponsor">
              {getFieldDecorator('sponsor', {
                initialValue: this.props.user.currentUser.name,
                rules: [
                  { required: true, message: "请输入发起人", },
                ],
              })(<Input placeholder={"H5工坊管理员"} disabled />)}
            </FormItem>
            <FormItem {...formItemLayout} label="开奖条件" key="style">
              {getFieldDecorator('style', {
                initialValue: (queryRow.style || queryRow.style === 0) ? String(queryRow.style) : undefined,
                rules: [
                  { required: true, message: "请选择开奖条件", },
                ]
              })(
                <Select placeholder="请选择开奖条件" style={{ width: '100%' }}>
                  <Option value="0">按时间自动开奖</Option>
                  <Option value="1">按人数自动开奖</Option>
                </Select>
              )}
            </FormItem>
            {
              (queryRow.style === 0 || getFieldValue('style') === '0')
              ?
              <FormItem {...formItemLayout} label="开奖日期" key="endAt">
                {getFieldDecorator('endAt', {
                  initialValue: queryRow.endAt ? moment(queryRow.endAt, 'YYYY-MM-DD HH:mm:ss') : null,
                  rules: [
                    { required: true, message: "请输入开奖日期", },
                  ],
                })(<DatePicker 
                    showTime
                    disabledDate={disabledDate}
                    format="YYYY-MM-DD HH:mm:ss"
                    style={{ width: '100%' }} 
                  />
                )}
              </FormItem>
              :
              (queryRow.style === 1 || getFieldValue('style') === '1')
              ?
              <FormItem {...formItemLayout} label="开奖人数" key="number">
                {getFieldDecorator('number', {
                  initialValue: queryRow.number || 1,
                  rules: [
                    { required: true, message: "请输入开奖人数", },
                  ],
                })(<InputNumber min={1} max={10000} />)}
              </FormItem> 
              :
              null
            }
            <FormItem {...formItemLayout} label="奖品说明" key="remark">
              {getFieldDecorator('brief', {
                initialValue: queryRow.brief,
                rules: [
                  { required: true, message: "请输入奖品说明", },
                ],
              })(<TextArea placeholder="请输入奖品说明" rows={3} />)}
            </FormItem>            
            {/*
              <FormItem {...formItemLayout} label="奖品介绍" key="brief">
                {getFieldDecorator('brief', {
                  initialValue: queryRow.brief,
                  rules: [
                    { required: true, message: "请输入奖品介绍", },
                  ],
                })(<TextArea placeholder="请输入奖品介绍" rows={3} />)}
              </FormItem>
            */}
            {formItems2}
            <FormItem {...submitFormLayout}>
              <Button type="dashed" onClick={this.addImageText} style={{ width: '100%' }}>
                <Icon type="plus" /> 增加介绍
              </Button>
            </FormItem>
            <FormItem {...submitFormLayout}>
              <Button type="primary" htmlType="submit" loading={submitting} size="large" style={{width: '100%'}}>
                确认
              </Button>
            </FormItem>
          </QueueAnim>
        </Card>
      </Fragment>
    );
  }
}

export default dynamic({
  loader: async function(payload) {
    return (payload) => <BasicForms {...payload} />;
  },
});